package org.xtframe.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessInstance;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.CommonUtil;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.JbpmUtil;
import org.xtframe.util.WorkflowUtil;

@Service
@Scope("prototype")
public class StartProcessDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆执行获取流程实例列表", 1);
			}
			
			JSONObject objJson = JSONObject.fromObject(strData);
			if(!objJson.has("id")) throw new AjaxDataHandlerException("流程定义ID为空");
			
			String processDefinitionId = objJson.optString("id");
			String processName = null;
			if(objJson.has("processName")){
				processName = objJson.optString("processName");
			} else {
				ProcessDefinition processDefinition = JbpmUtil.getInstance().getRepositoryService().createProcessDefinitionQuery()
						.processDefinitionId(processDefinitionId).uniqueResult();
				processName = processDefinition.getName();
			}
			
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("owner", userData.getUser().getUserId());
			ProcessInstance processInstance = JbpmUtil.getInstance().startProcessInstanceById(processDefinitionId, variables);
			
			try {
				if(WorkflowUtil.startProcess(processInstance.getId(), processName, 
						userData.getUser().getUserId(), CommonUtil.getCurrentTime())) {
					map.put(STATUS, true);
					map.put(ID, processInstance.getId());
				} else {
					map.put(STATUS, false);
					//删除流程实例
					JbpmUtil.getInstance().getExecutionService().deleteProcessInstanceCascade(processInstance.getId());
				}
			} catch (Exception e) {
				//删除流程实例
				JbpmUtil.getInstance().getExecutionService().deleteProcessInstanceCascade(processInstance.getId());
				throw e;
			}
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
